#include "stdafx.h"
#include "../3ds/io/io3ds.h"
#include "render/rendermgr.h"
#include "./pixelbitmap.h"

PixelBitmap::PixelBitmap(string strPath, Point pos, float z)
{
	m_texid = LoadFile(strPath, pos, z);
	RenderMgr::GetInstance().OnRender += EventObject<OnRenderFunc>(this, &PixelBitmap::OnRender);
}

PixelBitmap::~PixelBitmap()
{
	RenderMgr::GetInstance().OnRender -= EventObject<OnRenderFunc>(this, &PixelBitmap::OnRender);
	glDeleteLists(m_texid, 1);
}

unsigned int PixelBitmap::LoadFile(string strPath, Point pos, float z)
{
	unsigned int texid = -1;

	ImageData imagedata = GetImageData(strPath);
	if (imagedata.bSucceeded)
	{
		texid = GetDrawList(imagedata, pos, z);
	}
	imagedata.ReleaseBuffer();

	return texid;
}

ImageData PixelBitmap::GetImageData(string strJpegPath)
{
	ImageData data;

	size_t jpegsize = IO3ds::GetInstance().ReadFile(strJpegPath, NULL, 0);
	byte* buffer = new byte[jpegsize];

	size_t rb = IO3ds::GetInstance().ReadFile(strJpegPath, buffer, jpegsize);
	if (rb != jpegsize)
	{
		data.bSucceeded = false;
		return data;
	}

	JpegDecoder decoder(buffer, rb);
	data = decoder.GetImageData();

	delete[] buffer;
	return data;
}

unsigned int PixelBitmap::GetDrawList(ImageData& data, Point pos, float z)
{
	unsigned int texid = glGenLists(1);
	glNewList(texid, GL_COMPILE);
	glPushMatrix();
	glTranslatef(0, 0, z);
	glRasterPos2f(pos.x, pos.y);
	glDrawPixels(data.nWidth, data.nHeight, GL_RGBA, GL_UNSIGNED_BYTE, data.pBuffer);
	glPopMatrix();
	glEndList();

	return texid;
}

void PixelBitmap::OnRender(float differTime)
{
	if (!m_bVisible)
		return;

	glCallList(m_texid);
}